package myJs.user.soft

import japgolly.scalajs.react.component.Scala.Unmounted
import myJs.Implicits._
import myJs.Utils._

import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.myPkg.{BootstrapValidator, ColumnOptions, LayerOptions, TableOptions}
import myJs.tool.Pojo.{AnnoSoft, FilterContentData}
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.user.data.DataManage
import myJs.user.soft.fileSelect.{FileModal, MetSelectTab, MissionResultSelectTab, VarInfoSelectTab}
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._
import shared.Pojo._
import shared._

import scala.collection.immutable.SeqMap
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import upickle.default._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("Anno")
object Anno {
  val formId = "form"
  val kind = AnnoSoft.nameStr
  val fileModalId = "fileModal"
  val tableId = "table"
  val timeFieldNames = List[String]()

  @JSExport("init")
  def init = {
    FileModal.init
    registerEvent

    bootStrapValidator
    $("#form").bv.revalidateField("missionName")

    Tool.refreshCalculateConfigByJsonFile { rs =>
      val data = getData(rs)
    }
    VideoCp.Props(soft=AnnoSoft).render.renderIntoDOM(document.querySelector("#videoRoot"))

    //    fileSelectShow

  }

  def getData(rs: JDJAn) = {
    read[SharedAnnoData](JSON.stringify(rs))
  }

  def getMissionId = {
    g.missionId.toString
  }

  def registerEvent = {
    $(document.body).on("click", ".myRun", "", (y: Element) => {
      myRun
    })
    $(document.body).on("click", ".myFileSelectButton", "", (y: Element) => {
      val folder = $(y).dataFolder
      val fileName = $(y).dataFileName
      Tool.fileSelect(folder, fileName)
    })
    $(document.body).on("click", ".myFileSelect", "", (y: Element) => {
      val lis = $(y).dataValue.split(";")
      $(".myFileSelect").removeClass("myCurrent")
      $(y).addClass("myCurrent")
      FileModal.fileSelectShow(lis)
    })
  }

  @JSExport("myRun")
  def myRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.SoftController.analysis().url.toString
      val formData = $(s"#form").serialize()
      Tool.toggle2Boolean($(s"#${formId}"))
      Ajax.post(url = s"${url}", data = s"${formData}&kind=${AnnoSoft.nameStr}", headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        layer.close(index)
        val valid = rs("valid").toB
        if (valid) {
          window.location.href = g.jsRoutes.controllers.MissionController.missionManageBefore().url.toString
        } else {
          g.swal("Error", rs.myGet("message"), "error")
        }
      }
    }
  }

  def getId = {
    g.id.toString
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.MissionController.missionNameCheck().url.toString
    val fileNameCheckUrl = g.jsRoutes.controllers.SoftController.fileNameCheck().url.toString

    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
         "missionName" ->{
          val info=messages("taskName")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("exist")}",
                "url" -> url,
                "type" -> "POST",
                "delay" -> 1000,
                "data" -> js.Dictionary(
                  "kind" -> kind
                )
              ),
            )
          )
        },
        "file" -> {
          val info = s"${messages("dataMatrix")}"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("notExist")}",
                "url" -> fileNameCheckUrl,
                "type" -> "POST",
                "delay" -> 1000,
                "name" -> "fileName",
              ),
            )
          )
        },
      )
    )

    $(s"#form").bootstrapValidator(dict)
  }


}
